<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use User\Api\UserApi as UserApi;

/**
 * 后台首页控制器
 *
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class RoseController extends AdminController {

	/**
	 * 猜涨跌活动列表
	 *
	 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
	 */
	public function index() {
        if(isset($_GET['periods'])){
            $where['periods']=I('get.periods','','intval');
            $this->assign('periods',I('get.periods'));
        }
        if(isset($_GET['time'])){
            $where['time']=I('get.time','','intval');
            $this->assign('time',I('get.time'));
        }
        $this->meta_title = '猜涨跌活动列表';
        $total        =  D('rose_activity')->where($where)->count();
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        $page = new \Think\Page($total, $listRows, $REQUEST);
        $limit=$page->firstRow.','.$page->listRows;

        $list=D('rose_activity')->where($where)->order('periods asc,id desc')->limit($limit)->select();
        if($total>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $this->list=$list;
		$this->display();
	}

    /**
     * 删除猜涨跌活动列表
     */
    public function del(){
        $id     =   I('id','');
        if(empty($id)){
            return false;
        }
        $id=is_array($id)?join(',',$id):$id;
        $date['id']=array('in',$id);
        if(D('rose_activity')->where($date)->delete()){
            $this->success('删除成功', U('Rose/index'));
        }else{
            $this->error(D('rose_activity')->getError());
        }
    }

    public function addNextPeriod(){

        if(IS_POST){    //提交操作
            $data = I('');
            $model = M('RoseActivity');
            $data['periods'] = intval($data['periods']);
            $data['periods_start_time'] = strtotime($data['periods_start_time']);
            $data['periods_end_time'] = strtotime($data['periods_end_time']);
            $checkRes = $this->check_activity_data($data);
            if(!$checkRes['status']){
                $this->error($checkRes['info']);
            }
            $data = $model->create($data);
            $res = $model->add($data);
            if(false !== $res){
                $this->success("添加成功！", U('Rose/index'));
            }else{
                $this->error($model->getError());
            }
        }else{  //显示操作
            $this->display();
        }
    }

    public function editNextPeriod(){
        $model = M('RoseActivity');
        if(IS_POST){    //提交操作
            $data = I('');
            $data['periods'] = intval($data['periods']);
            $data['periods_start_time'] = strtotime($data['periods_start_time']);
            $data['periods_end_time'] = strtotime($data['periods_end_time']);
            $checkRes = $this->check_activity_data($data);
            if(!$checkRes['status']){
                $this->error($checkRes['info']);
            }
            $data = $model->create($data);
            $res = $model->save($data);
            if(false !== $res){
                $this->success("修改成功！", U('Rose/index'));
            }else{
                $this->error($model->getError());
            }
        }else{  //显示操作
            $id = I('get.id');
            $periods = $model->find($id);
            $this->assign('periods',$periods);
            $this->display();
        }
    }

    private function check_activity_data($data){
        $info = array();
        if(!is_int($data['periods']) || $data['periods']<=0){
            $info['status'] = false;
            $info['info'] = '期数必须是一个大于0的整数';
            return $info;
        }
        //判断期数是否已存在
        $where = array();
        $where['periods'] = $data['periods'];
        if(isset($data['id']) && !empty($data['id'])){
            $where['id'] = array('neq',$data['id']);
        }
        $model = M('RoseActivity');
        $has = $model->where($where)->count();
        if($has){
            $info['status'] = false;
            $info['info'] = '期数已存在';
            return $info;
        }
        if(!$data['periods_start_time'] || !$data['periods_end_time'] || $data['periods_start_time']>$data['periods_end_time']){
            $info['status'] = false;
            $info['info'] = '请输入正确的期数时间';
            return $info;
        }
        return array('status'=>true);
    }

    /**
     * 查看排名
     */
    public function ranking_list(){

        $where['periods'] = I('get.periods',0,'intval');
        $where['profit_gold_bean'] = array('neq',0);
        $this->meta_title = '第'.$where['periods'].'期排名';
       // $total = M('RoseBuy')->where($where)->group('user_id')->select();
       // $total=count($total);
       // echo M('RoseBuy')->getlastsql();
       // $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
       // $listRows=1;
      //  $page = new \Think\Page($total, $listRows, $REQUEST);
      //   $limit=$page->firstRow.','.$page->listRows;
       // $list = M('RoseBuy')->field("user_id,sum(profit_gold_bean) as bean,count(*) as bits,min(date) as min_date,max(date) as max_date,max(add_time) as max_time")->where($where)->group('user_id')->order('bean desc,bits desc,min_date asc,max_date desc,max_time asc')->limit($limit)->select();
        $list = M('RoseBuy')->field("user_id,sum(profit_gold_bean) as bean,count(*) as bits,min(date) as min_date,max(date) as max_date,max(add_time) as max_time")->where($where)->group('user_id')->order('bean desc,bits desc,min_date asc,max_date desc,max_time asc')->select();

        // if($total>$listRows){
        //    $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
       // }
       //  $p =$page->show();
     //   $this->assign('_page', $p? $p: '');
      //  $this->assign('_total',$total);
       // dump($list);
        //检索
        if(isset($_GET['nickname']) && !empty($_GET['nickname'])){
            $nickname=I('get.nickname','','trim');
            $user_id=get_table_field($nickname,'nickname','id','follow');
            foreach($list as $key=>$val){
                if($val['user_id'] == $user_id){
                    $list=array();
                    $list[$key]['user_id']=$user_id;
                    $list[$key]['bean']=$val['bean'];
                    break;
                }
            }
        }
        $this->list=$list;
        $this->assign('periods', $where['periods']);
        //活动信息
        $activity_info=get_table_field($where['periods'],'periods','','rose_activity');
        //如果活动结束并且未生成中奖用户 则显示生成中奖用户按钮
        if(!$activity_info['is_prized']){
            $this->assign('tag', 1);
        }


        $this->display();
    }
    /**
     * 查看中奖名单
     */
    public function win_list(){
        $where['periods'] = I('get.periods',0,'intval');
        $this->meta_title = '第'.$where['periods'].'期中奖名单';
        $total        =  D('win_log')->where($where)->count();
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        $page = new \Think\Page($total, $listRows, $REQUEST);
        $limit=$page->firstRow.','.$page->listRows;

        $list=D('win_log')->where($where)->order('win_id')->limit($limit)->select();
        if($total>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $this->list=$list;
        //$this->assign('periods',$where['periods']);
      // dump($list);
        $this->display();
    }

    /**
     * 生成中奖名单
     */
    public function build_win_list(){
        $periods = I('get.periods',0,'intval');
        $end_time=M('rose_activity')->where("periods=$periods")->getField('periods_end_time');
        //如果今天不是这一期活动的结束日 或者当前时间是小于3点10分
        if(date('Ymd',$end_time)!=date('Ymd') || time()<mktime(15,10,00,date('m'),date('d'),date('Y'))){
            $this->error('操作失败,只有在这期活动最后一天的下午3点10分以后才能生成中奖名单', U('Rose/index'));
        }
        $count=M('win_log')->where("periods=$periods")->count();
        if($count>0){
            $this->error('操作失败,已生成过中奖名单，不能重复生成', U('Rose/win_list',array('periods'=>$periods)));
        }
        $where['profit_gold_bean'] = array('neq',0);
        $where['periods']=$periods;
        //用户排行列表
        $where['periods']=$periods;
        $ranklist = M('RoseBuy')->field("user_id,sum(profit_gold_bean) as bean,count(*) as bits,min(date) as min_date,max(date) as max_date,max(add_time) as max_time")->where($where)->group('user_id')->order('bean desc,bits desc,min_date asc,max_date desc,max_time asc')->select();
        //奖品列表
        $prize_list=M('rose_prize')->where("periods=$periods")->select();
        $num=count($prize_list);
        $k=0;
        $data=array();
        for($i=0;$i<$num;$i++){
            $len=$prize_list[$i]['prize_num'];
            for($j=0;$j<$len;$j++){
                if(isset($ranklist[$k]['user_id'])){
                    $data[$k]['user_id']=$ranklist[$k]['user_id'];
                    $data[$k]['rose_prize_id']=$prize_list[$i]['id'];
                    $data[$k]['periods']=$periods;
                    $data[$k]['add_time']=time();
                    $k++;
                }
            }
        }
        if(M('win_log')->addAll($data)){
            M('rose_activity')->where("periods=$periods")->setField(array('is_prized'=>1));
            $this->success('操作成功', U('Rose/win_list',array('periods'=>$periods)));
        }else{
            $this->error('操作失败', U('Rose/ranking_list',array('periods'=>$periods)));
        }
    }

}
